<?php

namespace App\Http\Clients;

use GuzzleHttp\Client;
use GuzzleHttp\Exception\GuzzleException;
use App\Utils\TimeUtils;
class ShuMaiDataClient
{
    public $appId;

    public $security;

    public function __construct()
    {
        $this->appId = env('SHUMAIDATA_APPID');
        $this->security = env('SHUMAIDATA_APP_SECURITY');
    }

    // TODO 需要根据业务更换
    private static function setHostURL(): string
    {
        return config('resource.shumaidata.http_uri');
    }

    // TODO 需要根据业务更换
    private static function setTimeout(): int
    {
        return 3000;
    }

    private static function setHeaders(): array
    {
        return [
            'Content-Type' => 'application/json;charset=UTF-8',
            'Accept' => 'application/json'
        ];
    }

    public static function httpClient(): Client
    {
        return new Client([
            'base_uri' => self::setHostURL(),
            'timeout' => self::setTimeout(),
            'headers' => self::setHeaders()
        ]);
    }

    /**
     * 服务商分配的appid、当前时间毫秒数timestamp、商户分配的app_security、 三者通过&符号拼接成字符串进行md5加密得到。
     * @throws GuzzleException
     */
    public function sign()
    {
        //当前时间毫秒数
        $timestamp = TimeUtils::msectime();
        $str = $this->appId ."&".$timestamp ."&". $this->security;
        $sign = md5($str);
        return [
            'appid' => $this->appId,
            'timestamp' => $timestamp,
            'sign' => $sign
        ];
    }

    /**
     * 根据SDK返回的加密字符串获取活体检测结果以及人脸照片
     * @throws GuzzleException
     */
    public function facePhotos($packageName, $signData){
        try {
            $data = $this->sign();
            $data['packageName'] = $packageName;
            $data['signData'] = $signData;
            $response = self::httpClient()->request('POST',
                config('resource.shumaidata.face_photos'),
                [
                    'form_params' => $data
                ]
            );
            return $response->getBody()->getContents();
        } catch (GuzzleException $ex) {
            throw $ex;
        }
    }

    /**
     * 人脸身份证比对
     * @throws GuzzleException
     */
    public function faceIdCardCompare($idcard, $name, $image = null, $url= null)
    {
        try {
            $data = $this->sign();
            $data['idcard'] = $idcard;
            $data['name'] = $name;
            $data['image'] = $image;
            $data['url'] = $url;
            $response = self::httpClient()->request('POST',
                config('resource.shumaidata.comparison_of_certificates'),
                [
                    'form_params' => $data
                ]
            );
            return $response->getBody()->getContents();
        } catch (GuzzleException $ex) {
            throw $ex;
        }
    }

}
